package work.producer;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import constant.Constants;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created with IntelliJ IDEA.
 * Description：实现 RabbitMQ 的 工作模式下 客户端 -- 生产者
 *
 * @author: zxj
 * @date: 2024-09-18
 * @time: 14:25:51
 */
public class RabbitMQProducer {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 1. 创建工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 2. 设置参数
        factory.setHost(Constants.HOST);
        factory.setPort(Constants.PORT);
        factory.setVirtualHost(Constants.VIRTUAL_HOST);
        factory.setUsername(Constants.USERNAME);
        factory.setPassword(Constants.PASSWORD);
        // 3. 创建连接Connection
        Connection connection = factory.newConnection();
        // 4. 创建 channel
        Channel channel = connection.createChannel();

        // 5. 声明一个队列
        channel.queueDeclare(Constants.WORK_QUEUE_NAME, true, false, false, null);

        // 6. 通过 channel 发送消息到指定队列中
        // 生产者, 和简单模式下基本不变, 为了体现消费者之间的竞争, 生产者发送多条消息给消费者.
        for (int i = 0; i < 10; i++) {
            String msg = "hello rabbitmq, work" + i;
            channel.basicPublish("", Constants.WORK_QUEUE_NAME, null, msg.getBytes());
            System.out.println(msg + ": 消息发送成功");
        }

        // 7. 释放资源
        channel.close();
        connection.close();
    }
}
